import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class saleTicketDemo {
    //卖票
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(() -> {
            for (int i = 0; i < 50; i++) ticket.saleTicket();
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) ticket.saleTicket();
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) ticket.saleTicket();
        }, "C").start();
    }

}

class Ticket {

    private int num = 50;
    //公平非公平通过传入bool决定
    //不加锁有bug
    Lock lock = new ReentrantLock(true);

    public void saleTicket() {
        lock.lock();
        try {
            if (num >= 0) System.out.println(Thread.currentThread().getName() + "卖出票了，还剩" + num-- + "张");
        } finally {
            lock.unlock();
        }
    }

}